/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.elcom.emocbc.cbcgateway.ipc;

import com.elcom.ipc.synchronize.message.IPC_REQUEST;
import com.elcom.emocbc.common.ipc.message.cbcmessage.BROADCAST_SUBMIT_ACK;
import com.elcom.emocbc.common.ipc.message.cbcmessage.BROADCAST_SUBMIT_REQ;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author GiangLT
 */
public class IpcRejectedExecutionHandler implements RejectedExecutionHandler {

    private final Logger logger = LoggerFactory.getLogger(IpcRejectedExecutionHandler.class);

    @Override
    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
        logger.error("Thread pool overload");
        if (r instanceof HttpForwardTask) {
            IPC_REQUEST ipcRequest = ((HttpForwardTask) r).getRequest();
            if (ipcRequest instanceof BROADCAST_SUBMIT_REQ) {
                BROADCAST_SUBMIT_REQ request = (BROADCAST_SUBMIT_REQ) ipcRequest;
                BROADCAST_SUBMIT_ACK response = (BROADCAST_SUBMIT_ACK) request.createResponse();
                response.setErrorCode(BROADCAST_SUBMIT_ACK.BROADCAST_RESULT.OVERLOAD.value());
                response.setErrorDetail("Thread pool overloaded");
                
                request.sendResponse(response);
                logger.info("==> Sent response to [{}]: {}", ipcRequest.getEntityId(), response);
            }

        }
    }
}
